var WxParse = require('../../wxParse/wxParse.js');
var audioContext = wx.createInnerAudioContext();
//获取应用实例
var app = getApp()
Page({
  data: {
    isShowfl:false
  },
  onLoad:function(e){
    var that = this;
    if (e && e.scene) {
      var scene = decodeURIComponent(e.scene).split('&');
      console.log(scene);
      var secneObj = {};
      for (var i = 0; i < scene.length; i++) {
        var arr = scene[i].split('=');
        var key = arr[0];
        secneObj[key] = arr[1];
      }
      e = secneObj;
    }
    if(e&&e.id){
      that.setData({
        id:e.id
      })
    }
    if (e && e.type) {
      that.setData({
        fromType:e.type
      })
    }
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    var location = app.globalData.location;
    if (location && location.lat) {
      that.setData({
        curChooseLatitude: location.lat,
        curChooseLongitude: location.lng
      })
    }
  },
  onShow: function () {
    var that = this;
    if (!app.globalData.plumSession) {
      console.log("暂未获取到session");
      app.wechatSq(that);
    } else {
      app.requestAd(that);
      that.requestDetail();
    }
  },
  onUnload:function(){
    var that = this;
    if (that.data.fromType){
      var fromType = that.data.fromType;
      if (fromType == 'collect' && that.data.detailInfo.isCollection==0){
        console.log("详情页面卸载");
        console.log(that.data.id);
        wx.setStorageSync('removeCollectid', that.data.id)
      }
    }
    that.stopMusic('stop');
  },
  onHide:function(){
    var that = this;
    that.stopMusic('pause');
  },
  requestDetail: function () {
    var that = this;
    var data = {
      map: 'applet_mobile_shop_detail',
      sid: that.data.id
    };
    data.lng = that.data.curChooseLongitude ? that.data.curChooseLongitude : 0;
    data.lat = that.data.curChooseLatitude ? that.data.curChooseLatitude : 0;
    console.log(data);
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.setData({
            detailInfo: res.data.data
          })
          console.log(that.data.detailInfo);
          if (res.data.data.name){
            wx.setNavigationBarTitle({
              title: res.data.data.name
            })
          }
          
          var article = res.data.data.detail;
          // 富文本解析
          WxParse.wxParse('article', 'html', article, that, 5);
          that.playMusic();
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  makeCall: function (e) {
    var that = this;
    var mobile = e.currentTarget.dataset.mobile;
    wx.showModal({
      title: '',
      content: '拨打电话 ' + mobile,
      confirmText: '拨打',
      confirmColor: '#48C23D',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
              that.requestCall();
            },
            fail: function () {
              console.log("拨打电话失败！")

            }
          })
        }
      }
    })
  },
  openMap: function (e) {
    var latitude = e.currentTarget.dataset.lat;
    var longitude = e.currentTarget.dataset.lng;
    var address = e.currentTarget.dataset.address;
    var name = e.currentTarget.dataset.name;
    console.log(latitude + '--' + longitude + '--' + address + '--' + name)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: name,
      address: address,
      scale: 18
    })
  },
  toReportError:function(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subpages/reportError/reportError?id='+id,
    })
  },
  addContract:function(){
    var that = this;
    var name = that.data.detailInfo.name;
    var mobile = that.data.detailInfo.mobile;
    wx.addPhoneContact({
      firstName: name,
      mobilePhoneNumber: mobile,
      success:function(res){
        wx.showToast({
          title: '同步成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res){
        wx.showToast({
          title: '同步失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  requestCollect: function () {
    var that = this;
    var data = {
      map: 'applet_mobile_set_record',
      sid: that.data.id,
      type:'collect'
    };
    console.log(data);
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var detailInfo = that.data.detailInfo;
          detailInfo.isCollection = res.data.data.isCollection;
          that.setData({
            detailInfo: detailInfo
          })
          app.errorTip(that, res.data.data.msg, 2000);
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  requestCall: function () {
    var that = this;
    var data = {
      map: 'applet_mobile_set_record',
      sid: that.data.id,
      type: 'mobile'
    };
    console.log(data);
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          // app.errorTip(that, res.data.data.msg, 2000);
        } else {
          console.log(res.data)
          // app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  toclaimEnterprise:function(e){
    var id = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    var msg = e.currentTarget.dataset.msg;
    status = status ? status:'';
    msg = msg ? msg:'';
    wx.navigateTo({
      url: '/subpages/claimEnterprise/claimEnterprise?id=' + id +'&status=' + status + '&msg=' + msg,
    })
  },
  showSharemodal: function () {
    this.setData({
      isShowshare: true
    })
  },
  hideSharemodal: function () {
    this.setData({
      isShowshare: false
    })
  },
  peiviewPoster: function () {
    var that = this;
    var id = that.data.detailInfo.id;
    var data = {
      map: 'applet_mobile_shop_share',
      id: id
    }
    console.log(data);
    wx.showLoading({
      title: '海报生成中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var detailInfo = res.data.data;
          var curimg = detailInfo.shareImg;
          var imgs = [];
          imgs.push(curimg);
          wx.previewImage({
            current: curimg, // 当前显示图片的http链接
            urls: imgs // 需要预览的图片http链接列表
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  playMusic:function(){
    var that = this;
    var detailInfo = that.data.detailInfo;
    // 音频播放
    if (detailInfo.videoType == 2 && detailInfo.videoUrl) {
      audioContext.src = detailInfo.videoUrl;
      audioContext.startTime = 0;
      audioContext.onPlay(function(){
        var duration = parseInt(audioContext.duration);
        var currentTime = parseInt(audioContext.currentTime);
        that.setData({
          curPlaytime: that.formatPlayTime(currentTime),
          durationTime: that.formatPlayTime(duration),
          sumPlayTime: duration,
          curTimeStep: currentTime
        })
      });
      audioContext.onPause(function () {
        that.setData({
          isPlay: false
        })
      });
      audioContext.onTimeUpdate(function(){
        var duration = parseInt(audioContext.duration);
        var currentTime = parseInt(audioContext.currentTime);
        that.setData({
          curPlaytime: that.formatPlayTime(currentTime),
          durationTime: that.formatPlayTime(duration),
          curTimeStep: currentTime
        })
      });
      audioContext.onEnded(function () {
        that.setData({
          curPlaytime: that.formatPlayTime(0),
          curTimeStep: 0,
          isPlay:false
        })
      });
      audioContext.onStop(function(){
        that.setData({
          isPlay: false
        })
      });
      audioContext.onError(function () {
        app.errorTip(that,"音频播放错误", 2000);
        that.setData({
          curPlaytime: that.formatPlayTime(0),
          curTimeStep: 0,
          isPlay: false
        })
      });
    }
  },
  stopMusic:function(type){
    var that = this;
    var detailInfo = that.data.detailInfo;
    // 音频播放
    if (detailInfo.videoType == 2 && detailInfo.videoUrl && that.data.isPlay) {
      that.setData({
        isPlay: false
      })
      if (type == 'stop') {
        audioContext.stop();
      } else {
        audioContext.pause();
      }
    }
  },
  togglePlay:function(){
    var that = this;
    var detailInfo = that.data.detailInfo;
    // 音频播放
    if (detailInfo.videoType == 2 && detailInfo.videoUrl) {
      var isPlay = !that.data.isPlay;
      that.setData({
        isPlay: isPlay
      })
      if (that.data.isPlay) {
        audioContext.play();
      } else {
        audioContext.pause();
      }
    }
  },
  musicTimeChange:function(e){
    var that = this;
    var curVal = e.detail.value;
    if (that.data.isPlay){
      console.log(curVal)
      that.setData({
        curTimeStep: curVal,
        curPlaytime: that.formatPlayTime(curVal),
      })
      audioContext.seek(curVal);
    }
  },
  // 格式化音乐进度显示时间
  formatPlayTime: function (time) {
    var minute = parseInt(time / 60);
    var second = parseInt((time % 60));
    second = second < 10 ? '0' + second : second;
    var showTime = minute + ':' + second;
    return showTime;
  },
  onShareAppMessage:function(){
    var that = this;
    var id = that.data.id;
    var title = that.data.detailInfo.name;
    var shareInfo = app.globalData.shareInfo;
    title = shareInfo.shareTitle ? shareInfo.shareTitle : title;
    var cover = shareInfo.shareCover ? shareInfo.shareCover : '';
    app.getPoint(that);
    return {
      title: title,
      imageUrl: cover,
      path: '/subpages/shopInfoDetail/shopInfoDetail?enterfrom=share&&id=' + id
    }
  }
})
